package com.oocl.o2o.admin.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.oocl.o2o.admin.dao.MerchantDao;
import com.oocl.o2o.admin.entity.Merchant;

@Repository(value="merchantDaoImpl")
public class MerchantDaoImpl implements MerchantDao{
	
	@PersistenceContext(name="un")
	private EntityManager manager;
	
	@Override
	public Merchant findByName(String uname) {
		String jpql = "select m from Merchant m where m.uname=:uname";
		List<Merchant>merchantList = manager.createQuery(jpql)
				.setParameter("uname", uname)
				.getResultList();
		if (merchantList.isEmpty()) {
			return null;
		}
		else{
			return merchantList.get(0);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Merchant> findByStatus(int status) {
		String jpql = "select m from Merchant m where m.status=:status";
		List<Merchant> merchantList = manager.createQuery(jpql)
									.setParameter("status", status)
									.getResultList();
		if (merchantList.isEmpty()) {
			return null;
		}
		else{
			return merchantList;
		}	
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Merchant> findAll() {
		String jpql = "select m from Merchant m";
		List<Merchant> merchants = manager.createQuery(jpql).getResultList();
		if (merchants.isEmpty()) {
			return null;
		}
		else{
			return merchants;
		}	
	}

	@Override
	public Merchant add(Merchant merchant) {
		manager.persist(merchant);
		return merchant;
	}

	@Override
	public Merchant update(Merchant merchant) {
		Merchant m = manager.find(Merchant.class, merchant.getId());
		manager.clear();
		manager.merge(merchant);

		return merchant;
	}

	@Override
	public Merchant findById(String id) {
		String jpql = "select m from Merchant m where m.id=:id";
		List<Merchant> merchants = manager.createQuery(jpql)
				.setParameter("id", id)
				.getResultList();
		if (merchants.isEmpty()) {
			return null;
		}
		else{
			return merchants.get(0);
		}	
	}

}
